# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import json
import os
from itemadapter import ItemAdapter
from StockPro.func_stockindex import StockFunc
from StockPro.ClassStock import Stock
from StockPro.Analyze import analyzedata


class StockproPipeline:

    def process_item(self, item, spider):
        if not os.path.exists('./data'):
            os.makedirs('./data')
        with open("./data/" + item['code'] + ".csv", "wb") as fp:
            fp.write(item['all_data'])
        s = StockFunc()
        data = s.read(item['code'], item['name'])
        diff, dea, macd = s.MACD(data.closeprice, 12, 26, 9)
        cci = s.CCI(data.highprice, data.lowprice, data.closeprice, 14)
        k, d, j = s.KDJ(data.highprice, data.lowprice, data.closeprice, 9, 3, 3)
        if not os.path.exists('./result'):
            os.makedirs('./result')
        with open("./result/" + item['code'] + ".json", "w") as fp:
            json.dump({"diff": diff, "dea": dea, "macd": macd, "cci": cci, "k": k, "d": d, "j": j}, fp)
        analyzedata(data, macd, k, d, j, cci, item['code'])
        print("爬取股票{}成功！".format(item["code"]))
        return item
